package com.neusoft.yiyang.gateway.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springdoc.core.models.GroupedOpenApi;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class SwaggerAggregationConfig {

    private final RouteLocator routeLocator;

    public SwaggerAggregationConfig(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    @Bean
    public OpenAPI gatewayOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("医养系统 API 网关文档")
                        .description("聚合所有微服务的 API 接口文档，统一访问入口")
                        .version("1.0.0"));
    }

    @Primary
    @Bean
    public List<GroupedOpenApi> groupedOpenApis() {
        List<GroupedOpenApi> groups = new ArrayList<>();

        routeLocator.getRoutes().subscribe(route -> {
            String routeId = route.getId();
            if (routeId.endsWith("-service-route")) {
                String serviceName = routeId.replace("-route", "");
                String apiPath = "/api/" + serviceName.replace("-service", "") + "/v3/api-docs/**";

                groups.add(GroupedOpenApi.builder()
                        .group(serviceName)
                        .pathsToMatch(apiPath)
                        .build());
            }
        });

        return groups;
    }
}
